<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

    public function index(){
        $this->display();
    }

    /* 调用定时刷新token方法
    *
    */
    public function plan(){
    	G('begin'); //标记开始位置位置
		// ...其他代码段
		// $a = 1;
		// var_dump($a);
		echo '1//';


		G('end'); //标记结束位置位置
		// ...也许这里还有其他代码
		// 进行统计区间
		echo G('begin','end').'s'; //进行统计中间代码执行消耗时间
		echo G('begin','end','m').'kb'; //中间代码执行消耗内存开销统计
    }

    /**
	* 当日实时交易订单金额
    */
    public function dataOrderMoney(){

    	// G('begin'); //标记开始位置位置

    	//当日零点时间
    	$beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
    	$beginToday = $beginToday*1000;

    	//当前时间
    	$time = time()*1000;

    	$Model = new \Think\Model();
    	$orderData = $Model->query("select sum(payment_price) as totalMoney from __ORDER__ where `order_time` >= $beginToday AND `order_time` <= $time AND yn = 1 AND state in (20,25,30,90)");

    	$totalmoney = $orderData[0]['totalMoney'];

    	// G('end'); //标记结束位置位置

    	// echo G('begin','end').'s'; //进行统计中间代码执行消耗时间

    	// echo G('begin','end','m').'kb'; //中间代码执行消耗内存开销统计

    	echo $totalmoney;
    }

    /**
	* 当日实时交易订单量
    */
    public function dataOrderNumber(){

    	//当日零点时间
    	$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
    	$beginToday = $beginToday*1000;

    	//当前时间
    	$time = time()*1000;

    	$Model = new \Think\Model();
    	$orderData = $Model->query("select count(order_id) as ordersum from __ORDER__ where `order_time` >= $beginToday AND `order_time` <= $time AND yn = 1 AND state in (20,25,30,90)");

    	$ordersum = $orderData[0]['ordersum'];

    	echo $ordersum;
    }

    /**
	* 当月、本年实时交易订单
	* @param currentDateData number 当月交易数据
	* @param currentMonthData number 本年交易数据
    */
    public function monthOrder(){

    	//当月1日零点
    	$beginThismonth = mktime(0,0,0,date('m'),1,date('Y'));
    	$beginThismonth = $beginThismonth*1000;

    	//昨天的23:59:59
    	$endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
    	$endYesterday = $endYesterday*1000;

    	$Model = new \Think\Model();
    	$month_orderData = $Model->query("select sum(payment_price) as sumDealMoney, count(order_id) as sumOrderQuantity from __ORDER__ where `order_time` >= $beginThismonth AND `order_time` <= $endYesterday AND yn = 1 AND state in (20,25,30,90)");


    	//本年开始
    	$begin_year = strtotime(date("Y",time())."-1"."-1");
    	$begin_year = $begin_year*1000;

    	//上个月结束时间
    	$end_time = strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day'))); 
    	$end_time = $end_time*1000;

    	$Model = new \Think\Model();
    	$year_orderData = $Model->query("select sum(payment_price) as sumDealMoney, count(order_id) as sumOrderQuantity from __ORDER__ where `order_time` >= $begin_year AND `order_time` <= $end_time AND yn = 1 AND state in (20,25,30,90)");

    	$total_orderData = array(
    		'currentDateData'=>array(
    			"sumDealMoney"=>$month_orderData[0]['sumDealMoney'],
	    		"sumOrderQuantity"=>$month_orderData[0]['sumOrderQuantity'],
    		),
    		'currentMonthData'=>array(
    			"sumDealMoney"=>$year_orderData[0]['sumDealMoney'],
	    		"sumOrderQuantity"=>$year_orderData[0]['sumOrderQuantity'],
    		),
    	);

    	$total_orderData = json_encode($total_orderData);
    	echo $total_orderData;
    }

    /**
	* 地图(显示每个省区域的交易额)
	* 
    */
    public function map(){

    	//本年开始
    	$begin_year = strtotime(date("Y",time())."-1"."-1");
    	$begin_year = $begin_year*1000;

    	$Model = new \Think\Model();
    	$orderData = $Model->query("select b.name, SUM(a.payment_price) as value from __ORDER__ as a
									left join __PROVINCE__  as b on a.province_id=b.province_id
									WHERE a.order_time >= $begin_year AND a.yn = 1 AND a.state in (20,25,30,90)
									GROUP BY b.name");

    	$orderData = json_encode($orderData);
    	echo $orderData;
    }

    /**
	* 地图(已弃用)
	* @param provinceData array 省区域
    */
    public function dis_map(){

    	//本年开始
    	$begin_year = strtotime(date("Y",time())."-1"."-1");
    	$begin_year = $begin_year*1000;

    	$provinceData = array(
    		"北京市",
			"天津市",
			"上海市",
			"重庆市",
			"河北省",
			"河南省",
			"云南省",
			"辽宁省",
			"黑龙江省",
			"湖南省",
			"安徽省",
			"山东省",
			"新疆维吾尔自治区",
			"江苏省",
			"浙江省",
			"江西省",
			"湖北省",
			"广西壮族自治区",
			"甘肃省",
			"山西省",
			"内蒙古自治区",
			"陕西省",
			"吉林省",
			"福建省",
			"贵州省",
			"广东省",
			"青海省",
			"西藏自治区",
			"四川省",
			"宁夏回族自治区",
			"海南省",
			"台湾省",
			"香港特别行政区",
			"澳门特别行政区"
    	);

    	$Model = new \Think\Model();
    	foreach ($provinceData as $key => $value) {
    		$orderData[] = $Model->query("select sum(payment_price) as ordermoney from __ORDER__ where order_time >= $begin_year AND full_address like '$value%' AND yn = 1 AND state in (20,25,30,90)");
    	}

    	$mapData = array(
    		array(
    			"name"=>"北京",
	    		"value"=>$orderData[0][0]['ordermoney'],
    		),
    		array(
    			"name"=>"天津",
	    		"value"=>$orderData[1][0]['ordermoney'],
    		),
    		array(
    			"name"=>"上海",
	    		"value"=>$orderData[2][0]['ordermoney'],
    		),
    		array(
    			"name"=>"重庆",
	    		"value"=>$orderData[3][0]['ordermoney'],
    		),
    		array(
    			"name"=>"河北",
	    		"value"=>$orderData[4][0]['ordermoney'],
    		),
    		array(
    			"name"=>"河南",
	    		"value"=>$orderData[5][0]['ordermoney'],
    		),
    		array(
    			"name"=>"云南",
	    		"value"=>$orderData[6][0]['ordermoney'],
    		),
    		array(
    			"name"=>"辽宁",
	    		"value"=>$orderData[7][0]['ordermoney'],
    		),
    		array(
    			"name"=>"黑龙江",
	    		"value"=>$orderData[8][0]['ordermoney'],
    		),
    		array(
    			"name"=>"湖南",
	    		"value"=>$orderData[9][0]['ordermoney'],
    		),
    		array(
    			"name"=>"安徽",
	    		"value"=>$orderData[10][0]['ordermoney'],
    		),
    		array(
    			"name"=>"山东",
	    		"value"=>$orderData[11][0]['ordermoney'],
    		),
    		array(
    			"name"=>"新疆",
	    		"value"=>$orderData[12][0]['ordermoney'],
    		),
    		array(
    			"name"=>"江苏",
	    		"value"=>$orderData[13][0]['ordermoney'],
    		),
    		array(
    			"name"=>"浙江",
	    		"value"=>$orderData[14][0]['ordermoney'],
    		),
    		array(
    			"name"=>"江西",
	    		"value"=>$orderData[15][0]['ordermoney'],
    		),
    		array(
    			"name"=>"湖北",
	    		"value"=>$orderData[16][0]['ordermoney'],
    		),
    		array(
    			"name"=>"广西",
	    		"value"=>$orderData[17][0]['ordermoney'],
    		),
    		array(
    			"name"=>"甘肃",
	    		"value"=>$orderData[18][0]['ordermoney'],
    		),
    		array(
    			"name"=>"山西",
	    		"value"=>$orderData[19][0]['ordermoney'],
    		),
    		array(
    			"name"=>"内蒙古",
	    		"value"=>$orderData[20][0]['ordermoney'],
    		),
    		array(
    			"name"=>"陕西",
	    		"value"=>$orderData[21][0]['ordermoney'],
    		),
    		array(
    			"name"=>"吉林",
	    		"value"=>$orderData[22][0]['ordermoney'],
    		),
    		array(
    			"name"=>"福建",
	    		"value"=>$orderData[23][0]['ordermoney'],
    		),
    		array(
    			"name"=>"贵州",
	    		"value"=>$orderData[24][0]['ordermoney'],
    		),
    		array(
    			"name"=>"广东",
	    		"value"=>$orderData[25][0]['ordermoney'],
    		),
    		array(
    			"name"=>"青海",
	    		"value"=>$orderData[26][0]['ordermoney'],
    		),
    		array(
    			"name"=>"西藏",
	    		"value"=>$orderData[27][0]['ordermoney'],
    		),
    		array(
    			"name"=>"四川",
	    		"value"=>$orderData[28][0]['ordermoney'],
    		),
    		array(
    			"name"=>"宁夏",
	    		"value"=>$orderData[29][0]['ordermoney'],
    		),
    		array(
    			"name"=>"海南",
	    		"value"=>$orderData[30][0]['ordermoney'],
    		),
    		array(
    			"name"=>"台湾",
	    		"value"=>$orderData[31][0]['ordermoney'],
    		),
    		array(
    			"name"=>"香港",
	    		"value"=>$orderData[32][0]['ordermoney'],
    		),
    		array(
    			"name"=>"澳门",
	    		"value"=>$orderData[33][0]['ordermoney'],
    		),
    	);

    	$mapData = json_encode($mapData);
    	echo $mapData;
    }

    /**
	* 实时交易订单
    */
    public function realOrder(){

    	//本年开始
    	$begin_year = strtotime(date("Y",time())."-1"."-1");
    	$begin_year = $begin_year*1000;

    	$Model = new \Think\Model();
    	// $orderData = $Model->query("select b.shop_name, a.payment_price, a.order_time from __ORDER__ as a
					// 				LEFT JOIN __SHOPINFO__ as b ON a.shop_id=b.shop_id
					// 				WHERE a.order_time > $begin_year
					// 				order by a.order_time desc limit 2");

    	$orderData = $Model->query("select b.shop_name as storeName, a.payment_price as totalMoney, FROM_UNIXTIME(a.order_time/1000) as createTime from __ORDER__ as a
									LEFT JOIN __SHOPINFO__ as b ON a.shop_id=b.shop_id
									WHERE a.order_time > $begin_year
									order by a.order_time desc limit 2");

    	$orderData = json_encode($orderData);
    	echo $orderData;
    }

    /**
    * 获取最新的时间段内的订单
    */
    public function realtime(){
    	$start = I('get.start');
    	$end = I('get.end');

    	//直接访问方法，$start、$end 为空，sql语句执行会报错
    	if (!$start) {
    		$this->error('非法访问！');
    	}
    	
    	$Model = new \Think\Model();
    	$orderData = $Model->query("select b.shop_name as storeName, a.payment_price as totalMoney, FROM_UNIXTIME(a.order_time/1000) as createTime from __ORDER__ as a LEFT JOIN __SHOPINFO__ as b ON a.shop_id=b.shop_id WHERE a.order_time >= $start AND a.order_time <= $end");

    	$orderData = json_encode($orderData);
    	echo $orderData;
    }


    /*
    * B端店铺销量统计，获取销量前8名的店铺信息
    */
    public function shopsales(){

    	//当前时间
    	$currenttime = time();
    	$currenttime = $currenttime*1000;

    	$Model = new \Think\Model();
    	// $orderData = $Model->query("select b.shop_name as name, ROUND(SUM(a.payment_price)) as value FROM __ORDER__ as a LEFT JOIN __SHOPINFO__ as b ON a.shop_id=b.shop_id WHERE UNIX_TIMESTAMP(DATE_SUB(FROM_UNIXTIME($currenttime/1000),INTERVAL 30 DAY))*1000 <= a.order_time AND a.order_time <= $currenttime AND a.yn = 1 AND a.state in (20,25,30,90) GROUP BY a.shop_id ORDER BY SUM(a.payment_price) DESC LIMIT 8");

    	//筛选出店铺名称不为null的店铺信息
    	$orderData = $Model->query("select b.shop_name as name, ROUND(SUM(a.payment_price)) as value FROM __ORDER__ as a LEFT JOIN __SHOPINFO__ as b ON a.shop_id=b.shop_id WHERE IF(b.shop_name IS NOT NULL,UNIX_TIMESTAMP(DATE_SUB(FROM_UNIXTIME($currenttime/1000),INTERVAL 30 DAY))*1000 <= a.order_time AND a.order_time <= $currenttime AND a.yn = 1 AND a.state in (20,25,30,90),'') GROUP BY a.shop_id ORDER BY SUM(a.payment_price) DESC LIMIT 8");

    	// echo "<pre>";
    	// var_dump($orderData);
    	// exit();

    	$orderData = json_encode($orderData);
    	echo $orderData;
    }

    /**
	* 获取授权code
    */
    public function code(){
    	$jos_config = C('JOS_CONFIG');
    	$app_key=$jos_config['appKey'];
		$redirect_uri=$jos_config['redirect_uri'];

		$domain=urlencode("http://www.tlwok.com/");

		$url=$jos_config['code_url'];
		$url.="response_type=code";
		$url.="&client_id=".$app_key;
		$url.="&redirect_uri=".$redirect_uri;
		$url.="&state=1234";
		$url.="&scope=read";
		$url.="&domain=$domain";

		// https://oauth.jd.com/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&state=YOUR_CUSTOM_CODE

		// view 可选 移动端授权，该值固定为wap；非移动端授权，无需传值

		// echo $url;
		header("Location: $url"); 
		
    }

    /**
	* 授权
    */
    public function token(){
    	// echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
    	// echo $_SERVER['QUERY_STRING'];
    	$codeData = explode('=', $_SERVER['QUERY_STRING']);
    	// $getdata = $_GET;
    	// echo "<pre>";
    	// var_dump($codeData);
    	// exit();

    	$jos_config = C('JOS_CONFIG');
    	$app_key=$jos_config['appKey'];
		$app_secret=$jos_config['appSecret'];
		$redirect_uri=$jos_config['redirect_uri'];

		// $code = $getdata['code'];
		$code = $codeData['2'];
		// var_dump($code);
		// exit();

		$url=$jos_config['token_url'];
		$url.="grant_type=authorization_code";
		$url.="&client_id=$app_key";
		$url.="&redirect_uri=$redirect_uri";
		$url.="&code=$code";
		$url.="&state=1234";
		$url.="&client_secret=$app_secret";
		
		// https://oauth.jd.com/oauth/token?grant_type=authorization_code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=GET_CODE&state=YOUR_CUSTOM_CODE&client_secret= YOUR_APP_SECRET

		// 使用curl开源函数库来发送HTTP请求
		// 1. 初始化
		$ch=curl_init();
		 // 2. 设置选项，包括URL
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		//curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		//    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
		curl_setopt($ch,CURLOPT_URL,$url);
		//curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
		// 3. 执行并获取HTML文档内容,curl_exec() 执行CURL请求，如果没有错误发生，该函数的返回是对应URL返回的数据
		$output=curl_exec($ch);
		// 4. 释放curl句柄
		curl_close($ch);
		// echo $output;
		// exit();

		$output = json_decode($output,true);
		// echo '<pre>';
		// var_dump($output);
		// var_dump($output['uid']);
		// exit();

		$tokenModel = M('token');

		//每个店铺只保存一条token记录到数据库，多次授权同一个店铺只更新数据，不再新增
		$uid = $tokenModel->where('uid = \''.$output['uid'].'\'')->select(); 
		// echo '<pre>';
		// var_dump($uid);
		// exit();
		if ($uid) {
			$res = $tokenModel->where('id = \''.$uid[0]['id'].'\'')->save($output);
			if($res){
	            $this->success('获取token成功');
	            exit;
	        }else{
	            $this->error('已获取过token');
	            exit;
	        }
		} else {
			$res = $tokenModel->add($output);
			if($res){
	            $this->success('获取token成功');
	            exit;
	        }else{
	            $this->error('获取token失败');
	            exit;
	        }
		}
		
		

		// $path = __DIR__.'/jd_token_info.log';
		// if (file_exists($path)) {
		// 	unlink($path);
		// }

		// file_put_contents($path,$output,FILE_APPEND);
    }

    /**
	* 刷新token(新方法)
    */
    public function refreshToken(){

    	$tokenModel = M('token');
    	$tokenData = $tokenModel->getField('id,refresh_token,uid',true); //getField()查询指定字段，并且可以自定义键值

    	$jos_config = C('JOS_CONFIG');
	    $app_key=$jos_config['appKey'];
		$app_secret=$jos_config['appSecret'];

    	foreach ($tokenData as $key => $value) {
 
			$refresh_token= $value['refresh_token'];

			$url=$jos_config['token_url'];
			$url.="client_id=$app_key";
			$url.="&client_secret=$app_secret";
			$url.="&grant_type=refresh_token";
			$url.="&refresh_token=$refresh_token";

			$ch=curl_init();
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			//curl_setopt($ch,CURLOPT_POST,1);
			curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
			//    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
			curl_setopt($ch,CURLOPT_URL,$url);
			//curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
			$output=curl_exec($ch);
			curl_close($ch);
			// echo 'key:'.$key.$output."\n";
			// echo "<pre>";
			
			$output = json_decode($output,true);
			// var_dump($output);
			// $output['pid'] = '1';

			$res = $tokenModel->where('uid = \''.$value['uid'].'\'')->save($output);
			if($res){
	            $this->success('刷新token成功');
	        }else{
	            $this->error('刷新token失败');
	        }

    	}
    	exit;
    }

    /**
	* 刷新token(旧方法,已弃用)
    */
    public function dis_refreshToken(){
    	$path = __DIR__.'/jd_token_info.log';
    	if(file_exists($path)){ 
			$content = file_get_contents($path); 
			$content = iconv("GB2312","UTF-8//IGNORE",$content);  
			$data = json_decode($content,true); 
			// $error = json_last_error(); //5:错误编码
		}

		$time = $data['time']/1000+$data['expires_in'];
		if (time()>= $time) {
			$jos_config = C('JOS_CONFIG');

	    	$app_key=$jos_config['appKey'];
			$app_secret=$jos_config['appSecret'];
			$refresh_token= $data['refresh_token'];

			$url=$jos_config['token_url'];
			$url.="client_id=$app_key";
			$url.="&client_secret=$app_secret";
			$url.="&grant_type=refresh_token";
			$url.="&refresh_token=$refresh_token";

			$ch=curl_init();
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			//curl_setopt($ch,CURLOPT_POST,1);
			curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
			//    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
			curl_setopt($ch,CURLOPT_URL,$url);
			//curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
			$output=curl_exec($ch);
			curl_close($ch);
			echo $output;

			$path = __DIR__.'/jd_token_info.log';
			if (file_exists($path)) {
				unlink($path);
			}
			file_put_contents($path,$output,FILE_APPEND);
		}
    }

}